from django.shortcuts import render

# Create your views here.
from django.views import View
from .models import *
from rest_framework.views import APIView
from myapp import myserializers
from rest_framework.response import Response
from utils.captcha.captcha import captcha
from django.http import HttpResponse
import memcache
import requests
import json
from itsdangerous import TimedJSONWebSignatureSerializer as SerializerName
from django.conf import settings

server = memcache.Client(["39.106.229.25:11211"])


class RegisterView(APIView):
    def post(self, request):
        username = request.data.get("username")
        imagecode = request.data.get("imagecode")

        code = server.get(username)

        print(code)

        if imagecode.lower() != code.lower():
            return Response({'code': 500, 'data': '验证码错误'})

        user_ser = myserializers.UserSerializer(data=request.data)
        if user_ser.is_valid():
            user_ser.save()
            return Response({'code': 200, 'data': '创建成功'})
        else:
            return Response({'code': 500, 'data': '创建失败'})


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user_ser = User.objects.filter(username=username, password=password).first()
        if user_ser:
            serializer = SerializerName(settings.SECRET_KEY, 360)
            token = serializer.dumps({
                'id': user_ser.id,
                'username': username
            })
            return Response({
                'code': 200,
                'data': '登陆成功',
                'token': token.decode()
            })
        else:
            return Response({
                'code': 500,
                'data': '登陆失败,账号不存在'
            })


class Imges(APIView):  # 验证码
    def get(self, request):
        name, text, image = captcha.generate_captcha()
        response = HttpResponse(image)
        response["Content-Type"] = "image/jpg"
        username = request.GET.get('username')
        server.set(username, text, 60)
        return response


class WeiBoView(APIView):
    def post(self, request):
        token = request.data.get('token')
        params = {
            'client_id': '297351690',
            'client_secret': '8e24e86fd5dfa8d95675316bd969f9f1',
            'grant_type': 'authorization_code',
            'code': token,
            'redirect_uri': 'http://127.0.0.1:8080/weibo_callback'
        }
        url = 'https://api.weibo.com/oauth2/access_token'

        res = requests.post(url, data=params).text
        dict = json.loads(res)
        # print(dict['uid'])
        return Response({
            'code': 200,
            'uid': dict['uid']
        })


class WeiBoBindView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        uid = request.data.get('uid')
        # print(username, password, uid)

        user_yanzheng = User.objects.filter(username=username).first()
        if user_yanzheng:
            if user_yanzheng.password != password:
                return Response({
                    'code': 500,
                    'data': '用户或者密码错误'
                })
        else:
            User.objects.create(username=username, password=password)

        weibo = Weibo.objects.filter(uid=uid).first()
        if weibo:
            return Response({
                'code': 201,
                'data': '用户已绑定过，跳转登陆页面'
            })

        # 微博绑定表的添加
        user = User.objects.filter(username=username).first()
        Weibo.objects.create(uid=uid, user=user)

        return Response({
            'code': 200,
            'data': '绑定成功'
        })


class CateView(APIView):
    def get(self, request):
        uid = request.GET.get('id', 0)
        if uid == 0:
            cate_list = Cate.objects.all()
            cate_ser = myserializers.CateSerializer(instance=cate_list, many=True)
        else:
            cate = Cate.objects.filter(pk=uid).first()
            cate_ser = myserializers.CateSerializer(instance=cate)
        return Response({
            'code': 200,
            'data': cate_ser.data
        })

    def post(self, request):
        uid = request.data.get('id')
        # print(uid)
        if not uid:
            cate_ser = myserializers.CateSerializer(data=request.data)
            if cate_ser.is_valid():
                cate_ser.save()
                return Response({
                    'code': 200,
                    'data': '分类添加成功'
                })
            else:
                print(cate_ser.errors)
                return Response({
                    'code': 500,
                    'data': '分类添加失败'
                })
        else:
            name = request.data.get('newname')
            Cate.objects.filter(pk=uid).update(name=name)
            return Response({
                'code': 200,
                'data': '修改成功'
            })

    def delete(self, request):
        id = request.data.get('cid')
        Cate.objects.filter(pk=id).delete()
        return Response({
            'code': 200,
            'data': '删除成功'
        })


def TokenJie(token):
    serializer = SerializerName(settings.SECRET_KEY, 360)
    try:
        token = serializer.loads(token)
    except Exception as e:
        return None
    return token


class YanzView(APIView):
    def post(self, request):
        token = request.data.get('token')
        tokenyz = TokenJie(token)
        if not tokenyz:
            return Response({
                'code': 404,
                'data': '验证失败'
            })
        return Response({
            'code': 200,
            'data': '验证成功'
        })
